/*
 * Ant Group
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.zmdepositdemo.util;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayResponse;
import com.alipay.zmdepositdemo.model.OpenResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * AlipayApi模板
 *
 * @author zhangjian
 * @version AlipayApiTemplate.java, v 0.1 2024年06月14日 11:17 zhangjian
 */
public class AlipayApiTemplate {

    private static final Logger logger = LogManager.getLogger(AlipayApiTemplate.class);

    public static <T, R extends AlipayResponse> OpenResponse<T> execute(AlipayApiCallback<T, R> callback) {
        try {
            //执行
            R response = callback.process();
            OpenResponse<T> tOpenResponse = new OpenResponse<>(response);
            if (response.isSuccess()) {
                //获取data
                T data = callback.getData(response);
                tOpenResponse.setData(data);
                logger.info(callback.getApiName() + "调用成功：" + response.getBody());
            } else {
                logger.error(callback.getApiName() + "调用失败：" + JSON.toJSONString(response));
            }
            return tOpenResponse;
        } catch (AlipayApiException e) {
            //异常处理
            logger.error(callback.getApiName() + "调用失败", e);
            return new OpenResponse<>(e);
        } catch (Exception e) {
            //异常处理
            logger.error(callback.getApiName() + "调用失败", e);
            OpenResponse<T> response = new OpenResponse<>();
            response.setCode("SYSTEM_ERROR");
            response.setMsg("系统错误");
            response.setSubMsg(e.getMessage());
            return response;
        }
    }

}